//
//  ST_WaitChatRankViewController.swift
//  btvideo
//
//  Created by mac on 2020/12/29.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh

fileprivate var lastJoinEventDate:Date?

class ST_WaitChatRankViewController: ST_BTLightBarViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        self.title_nav_btn.setTitleForAllStates("等待通话")
        right_nav_btn.setImageForAllStates(ST_ImageUtils.imageName("视频语音匹配_plus_icon")!)
        right_nav_btn.isHidden = false
        
         
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 44 + statusBarHeight, left: 0, bottom: 0, right: 0))
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.fetch_boot_data()
        })

        fetch_boot_data()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(delete_notification(noti:)), name: ST_LiveBeautyWidget.delete_live_queue_notification, object: nil)
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
        
    }
    
    @objc fileprivate func delete_notification(noti:Notification){
        
        let json = JSON(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        guard let removeIndex = match_pool_array.firstIndex(where:({$0.accid == accid})) else{
            return
        }
        
        let index = Int(removeIndex.uInt)
        
        match_pool_array.remove(at: index)
        
//        collectionView.deleteItems(at: [IndexPath(row: index, section: 0)])
        
        self.reload_u_i()
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        
        currentPage += 1
        
        JVrequest(PH.fetchRecommendLiveApi,parameters: ["page":currentPage,"size":20]) { (json) in
            
            let array = json["data"].arrayValue.map({ST_TalkMatchPoolModel.init(fromJson: $0)})
            
            if self.currentPage == 1{
                self.match_pool_array = array
            }else{
                self.match_pool_array += array
            }
            
            self.reload_u_i()
            
            self.load_more_option_style(tableView: self.collectionView, count: array.count, pageSize: 20) {[weak self] in
                
                self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
            
        } failure: { (code, error) in
            
            self.reload_u_i()
            
            self.toast(text: error)
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
        }

        
        
    }
    
    fileprivate func fetch_boot_data(){
        
        currentPage = 0
        
        request_data()
    }
    
    
    fileprivate func reload_u_i(){
        
        if match_pool_array.count > 0{
            
            self.layout.headerReferenceSize = CGSize.zero
        }else{
            self.layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: ScreenHeight)
        }
        
        self.collectionView.reloadData()
        
    }
    
    override func right_click() {
        
        self.goback_previous_controller(animated: false) {
            
            ST_LiveBeautyWidget.shared.up_live_square_handle(sender: UIButton())
            
        }
    }
    
    fileprivate func push_begin_match(isVideo:Bool){
        
        
    }
    
    
    //     MARK: - Properties
    fileprivate var match_pool_array = [ST_TalkMatchPoolModel]()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 15
        controlLayout.minimumInteritemSpacing = 15
        controlLayout.sectionInset = UIEdgeInsets.init(top: 12, left: 15, bottom: BTSafeAreaBottom + 49, right: 15)
        let w = (ScreenWidth - 15*3)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w/165*160+70)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_WaitChatRankCell.self)
        
        //        header
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_WaitChatRankEmptyView.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.init(hexString: "#F5F8FA")
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    
    
}

extension ST_WaitChatRankViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    // MARK: UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return match_pool_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_WaitChatRankCell.self, for: indexPath)
        
        cell.model = match_pool_array[indexPath.row]
        
        return cell
    }
    
    // MARK: UICollectionViewDelegate
    //
    //    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    //
    //        guard let m = MatchForMeetDispatcher.shared.match_pool_array[safe:indexPath.row] else{
    //            return
    //        }
    //
    //        let vc = ST_PairsCenterViewController()
    //
    //        vc.accid = m.accid
    //
    //        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
    //
    //        nav.overCurrentContext = true
    //
    //        GlobalPresent(toController: nav)
    //
    //
    //    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_WaitChatRankEmptyView.self, for: indexPath)
        
        view.voiceChatClosure = {[weak self] in
            
            self?.goback_previous_controller(animated: false, completion: {
                self?.push_begin_match(isVideo: false)
            })
            
        }
        
        view.video_chat_closure = {[weak self] in
            
            self?.goback_previous_controller(animated: false, completion: {
                self?.push_begin_match(isVideo: true)
            })
        }
        
        return view
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        guard let viewModel = match_pool_array[safe:indexPath.row] else { return  }
        
        var isVideo:Bool?
        if viewModel.type == 2{
            isVideo = true
        }else if viewModel.type == 1{
            isVideo = false
        }else{
            
            self.toast(text: "对方忙，请稍后再试")
            
            return
        }
        
        guard let v = isVideo else { return  }
        
        
        
        ST_MediaChatDispatcher.shared.inviteChat(sessionId: viewModel.accid, isVideo: v,inviteDistract: "upLiveWall")
        
    }
}




//MARK: - Cell
class ST_WaitChatRankCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .white
        
        contentView.addSubview(cover_image_view)
        contentView.addSubview(gradient_view)
        contentView.addSubview(time_label)
        contentView.addSubview(titleLabel)
        contentView.addSubview(content_label)
        contentView.addSubview(chat_btn)
        
        contentView.cornerRadius = 20
        
        cover_image_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(cover_image_view.snp.width).dividedBy(165.0/160.0)
        }
        
        gradient_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
            make.bottom.equalTo(cover_image_view)
        }
        
        time_label.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(cover_image_view).offset(-5)
        }
        
        
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(cover_image_view.snp.bottom).offset(13)
            make.height.equalTo(17)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10-30-5)
        }
        
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.right.equalTo(chat_btn.snp.left).offset(-5)
            make.left.equalTo(titleLabel)
        }
        
        chat_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(36)
            make.centerY.equalTo(titleLabel.snp.bottom)
            make.right.equalToSuperview().offset(-10)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //    MARK: - Properties
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#333333")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = .white
        //        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        let control = ST_FWGradientView()
        
        control.bgLayer.colors = [UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 0).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
        control.bgLayer.locations = [0, 1]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        //        [UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 0).cgColor, UIColor(red: 0.02, green: 0.02, blue: 0.02, alpha: 0.2).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
        
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#61666F")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    fileprivate lazy var chat_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
//        control.add_touch_up(insideTarget: self, action: #selector(chat_handle))
        control.isUserInteractionEnabled = false
        return control
    }()
    
    fileprivate lazy var voiceImageIcon = ST_ImageUtils.imageName("WaitVoiceImageIcon")!
    
    fileprivate lazy var videoImageIcon = ST_ImageUtils.imageName("WaitVideoImageIcon")!
    
    //    MARK:-
    weak var model:ST_TalkMatchPoolModel?{
        didSet{
            
            guard let m = model else{
                return
            }
            
            cover_image_view.pin_setImage(from: m.avatar.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = m.nickname
            
            
            
            content_label.text = m.age.string + "岁" + " \(m.address)"
            
            if m.type == 1 {
                chat_btn.setImageForAllStates(voiceImageIcon)
                time_label.text =  "语音通话"
            }else{
                time_label.text =  "视频通话"
                chat_btn.setImageForAllStates(videoImageIcon)
            }
            
            
        }
    }
    
}
//MARK: - Empty View

class ST_WaitChatRankEmptyView: UICollectionReusableView {
    override init(frame: CGRect) {
        super.init(frame: frame)
      
        self.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.height.width.equalTo(120)
            make.top.equalToSuperview().offset(146)
            make.centerX.equalToSuperview()
        }
        
        
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(cover_image_view.snp.bottom).offset(10)
            make.height.equalTo(22)
        }
        
        
        self.addSubview(video_btn)
        video_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(content_label.snp.bottom).offset(50)
            make.height.equalTo(52)
            make.width.equalTo(245)
        }
        
        self.addSubview(voice_btn)
        voice_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(video_btn.snp.bottom).offset(15)
            make.height.equalTo(52)
            make.width.equalTo(245)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("wait_talk_empty_center_icon"))
              return control
          }()
    
    fileprivate lazy var content_label:UILabel = {
         let control = UILabel.init()
         control.text = "有超多人正在等你发起通话呢！"
         control.textColor = UIColor(hexString: "#ACB4C0")
         control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
         return control
     }()
        
    fileprivate lazy var video_btn:UIButton = {
            
            let control = UIButton.init(type: UIButton.ButtonType.custom)
            control.setImageForAllStates(ST_ImageUtils.imageName("wait_talk_empty_video_icon")!)
          
        
        control.addTarget(ST_MediaChatDispatcher.shared, action: #selector(ST_MediaChatDispatcher.match_video_handle(sender:)), for: UIControl.Event.touchUpInside)
        
            return control
        }()
    
    fileprivate lazy var voice_btn:UIButton = {
            
            let control = UIButton.init(type: UIButton.ButtonType.custom)
            control.setImageForAllStates(ST_ImageUtils.imageName("wait_talk_empty_voice_icon")!)
          
            control.addTarget(self, action: #selector(begin_voice_chat_handle), for: UIControl.Event.touchUpInside)
        
        
        control.addTarget(ST_MediaChatDispatcher.shared, action: #selector(ST_MediaChatDispatcher.match_voice_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        
            return control
        }()
    
    
    var voiceChatClosure:(()->())?
    @objc fileprivate func begin_voice_chat_handle(){
        voiceChatClosure?()
    }
    
    var video_chat_closure:(()->())?
    @objc fileprivate func begin_video_chat_handle(){
        video_chat_closure?()
    }
}


//MARK: - Model

class ST_TalkMatchPoolModel : NSObject{

    var accid : String
    var address : String
    var age : Int
    var avatar : String
    var birth : Int
    var channelName : String
    var nickname : String
    var type : Int
    var vdAddress : String

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        accid = json["accid"].stringValue
        address = json["address"].stringValue
        age = json["age"].intValue
        avatar = json["avatar"].stringValue
        birth = json["birth"].intValue
        channelName = json["channel_name"].stringValue
        nickname = json["nickname"].stringValue
        type = json["type"].intValue
        vdAddress = json["vd_address"].stringValue
        
        super.init()
    }
}
